﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using System.IO.Packaging;

namespace Exentials.Xoox.Spreadsheet
{
    public class XSpreadsheet : IDisposable
    {
        private SpreadsheetDocument _spreasheetDocument;
        private XWorkbook _xWorkbook;
        private MemoryStream _memoryStream;

        public XSpreadsheet()
        {
            _memoryStream = new MemoryStream();
            _spreasheetDocument = SpreadsheetDocument.Create(_memoryStream, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook);
            _xWorkbook = new XWorkbook(_spreasheetDocument.AddWorkbookPart());
        }

        public XWorkbook Workbook
        {
            get
            {
                return _xWorkbook;
            }
        }

        public void WriteTo(Stream stream)
        {
            _xWorkbook.Save();
            _spreasheetDocument.Close();
            _memoryStream.WriteTo(stream);
            _memoryStream.Flush();
        }

        public void Save(string path)
        {
            DocumentFormat.OpenXml.Validation.OpenXmlValidator validator = new DocumentFormat.OpenXml.Validation.OpenXmlValidator(DocumentFormat.OpenXml.FileFormatVersions.Office2007);
            
            _xWorkbook.Save();

            var errors = validator.Validate(_spreasheetDocument);

            _spreasheetDocument.Close();
                        
            using (FileStream f = File.Create(path))
            {
                _memoryStream.Position = 0;
                _memoryStream.WriteTo(f);
                _memoryStream.Flush();
                f.Close();
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this._memoryStream != null)
                {
                    this._memoryStream.Close();
                    this._memoryStream.Dispose();
                }
            }
        }

        ~XSpreadsheet()
        {
            Dispose(false);
        }

    }
}
